// utility.js

// The same as chrome.windows.getLastFocused, but compatible with all 
// currently supported Chrome versions.
function GetLastFocusedWindow(callback)
{
	try
	{
		chrome.windows.getLastFocused(null, callback);
	}
	catch(e)
	{
		chrome.windows.getLastFocused(callback);
	}
}

// Create a tab, eg. to show a new message in a non-incognito window
function CreateTab(relative_url)
{
	GetLastFocusedWindow(function(win)
	{
		if(!win.incognito && win.type == "normal")
			chrome.tabs.create({windowId: win.id, 
				url: XHR.GetURL(relative_url)});
		else
			chrome.windows.getAll(function(wins)
			{
				for(var i = 0; i < wins.length; ++i)
					if(!wins[i].incognito && wins[i].type == "normal")
					{
						chrome.tabs.create({windowId: wins[i].id, 
							url: XHR.GetURL(relative_url)});
						chrome.windows.update(wins[i].id, {focused: true});
						return;
					}
				//All windows found are incognito. Create a non-incognito
				//one, along with the new tab
				chrome.windows.create({url: XHR.GetURL(relative_url), 
					incognito: false, focused: true});
			});
	});
}

